package fr.esisar.p2014.cs420.nsmwnr;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class ModifierAlbum {
	Shell shell = null;
	private Display display = null;
	private Text text;
	private Text text_1;
	private CCombo combo;
	private CCombo combo_1;
	private List list;
	private Button btnAlbum;
	private Button btnLivre;
	private Button btnAfficherLesStatistiques;
	private Button btnSeConnecter;
	private Label lblVousNtesPas;

	private int [] idAlbums;
	private int [] idLivres;
	private int [] idPhotos;
	private Label lblMerciDeSlectionner;
	
	public ModifierAlbum(){
		display = MainApp.display;
	}
	
	public void setActive(){
		if(shell == null || shell.isDisposed()){
			run();
		}else{
			rafraichir();
			shell.setActive();
		}
	}
	/**
	 * @wbp.parser.entryPoint
	 */
	public void run(){

		shell = new Shell(display, SWT.SHELL_TRIM & ~SWT.RESIZE & ~SWT.MAX);		// Crée une fenêtre non redimensionnable
		shell.setText("Ajouter une photo à un album");
		shell.setSize(878, 433);
		shell.setImage(MainApp.icone);
		
		Label label = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setBounds(0, 41, 872, 15);
		
		btnSeConnecter = new Button(shell, SWT.NONE);
		btnSeConnecter.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				if(MainApp.idClient == 0)
					MainApp.conn.setActive();
				else
					MainApp.conn.deconnecter();
			}
		});
		btnSeConnecter.setBounds(782, 10, 80, 25);
		
		lblVousNtesPas = new Label(shell, SWT.NONE);
		lblVousNtesPas.setAlignment(SWT.RIGHT);
		lblVousNtesPas.setBounds(288, 15, 488, 15);
		
		Button btnRetourLa = new Button(shell, SWT.NONE);
		btnRetourLa.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				shell.dispose();
				MainApp.consult.setActive();
			}
		});
		btnRetourLa.setBounds(10, 10, 133, 25);
		btnRetourLa.setText("Retour à la consultation");
		
		btnAfficherLesStatistiques = new Button(shell, SWT.NONE);
		btnAfficherLesStatistiques.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				MainApp.stats.setActive();
			}
		});
		btnAfficherLesStatistiques.setBounds(149, 10, 133, 25);
		btnAfficherLesStatistiques.setText("Afficher les statistiques");
		
		Label lblObjetConcern = new Label(shell, SWT.NONE);
		lblObjetConcern.setBounds(10, 62, 87, 15);
		lblObjetConcern.setText("Objet concerné :");
		
		btnAlbum = new Button(shell, SWT.RADIO);
		btnAlbum.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				btnAlbum.setSelection(true);
				btnLivre.setSelection(false);
				rafraichirLesPhotos();
			}
		});
		btnAlbum.setSelection(true);
		btnAlbum.setBounds(103, 62, 90, 16);
		btnAlbum.setText("Album :");
		
		btnLivre = new Button(shell, SWT.RADIO);
		btnLivre.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				btnAlbum.setSelection(false);
				btnLivre.setSelection(true);
				rafraichirLesPhotos();
			}
		});
		btnLivre.setBounds(103, 83, 90, 16);
		btnLivre.setText("Livre :");
		
		combo = new CCombo(shell, SWT.BORDER | SWT.READ_ONLY);
		combo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				btnAlbum.setSelection(true);
				btnLivre.setSelection(false);
				rafraichirLesPhotos();
			}
		});
		combo.setBounds(199, 56, 222, 21);
		
		combo_1 = new CCombo(shell, SWT.BORDER | SWT.READ_ONLY);
		combo_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				btnAlbum.setSelection(false);
				btnLivre.setSelection(true);
				rafraichirLesPhotos();
			}
		});
		combo_1.setBounds(199, 78, 222, 21);
		
		Label lblImagesDisponibles = new Label(shell, SWT.NONE);
		lblImagesDisponibles.setBounds(10, 105, 107, 15);
		lblImagesDisponibles.setText("Images disponibles :");
		
		list = new List(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		list.setBounds(10, 126, 852, 152);
		
		text = new Text(shell, SWT.BORDER);
		text.setBounds(199, 284, 663, 21);
		
		Label lblTitreDeLimage = new Label(shell, SWT.NONE);
		lblTitreDeLimage.setBounds(41, 287, 152, 15);
		lblTitreDeLimage.setText("Titre de l'image dans l'objet :");
		
		text_1 = new Text(shell, SWT.BORDER);
		text_1.setBounds(199, 311, 663, 21);
		
		Label lblCommentaire = new Label(shell, SWT.NONE);
		lblCommentaire.setBounds(113, 314, 80, 15);
		lblCommentaire.setText("Commentaire :");
		
		Button btnAjouter = new Button(shell, SWT.NONE);
		btnAjouter.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				actionBouttonAjouter();
			}
		});
		btnAjouter.setBounds(696, 338, 166, 56);
		btnAjouter.setText("Ajouter");
		
		lblMerciDeSlectionner = new Label(shell, SWT.NONE);
		lblMerciDeSlectionner.setBounds(513, 379, 177, 15);
		lblMerciDeSlectionner.setVisible(false);
		
		rafraichir();
		shell.open();
	}
	
	public void actionBouttonAjouter(){
		int idAlbum;
		int numPlace;

		if(btnAlbum.getSelection() && combo.getSelectionIndex() < 0){
			lblMerciDeSlectionner.setText("Merci de choisir un album valide !");
			lblMerciDeSlectionner.setVisible(true);
			return;
		}
		if(btnLivre.getSelection() && combo_1.getSelectionIndex() < 0){
			lblMerciDeSlectionner.setText("Merci de choisir un livre valide !");
			lblMerciDeSlectionner.setVisible(true);
			return;
		}
		if(list.getSelectionCount() == 0){
			lblMerciDeSlectionner.setText("Merci de sélectionner une photo !");
			lblMerciDeSlectionner.setVisible(true);
			return;
		}
		if(btnAlbum.getSelection())
			idAlbum = idAlbums[combo.getSelectionIndex()];
		else
			idAlbum = idLivres[combo.getSelectionIndex()];
		

		Statement stmt;
		try {
			stmt = JDBC.getInstance().getStatement();
			stmt.executeUpdate("SET TRANSACTION READ WRITE");
			
			String req = "SELECT MAX(numPlace) FROM Contient WHERE idAlbum  = " + idAlbum;
			ResultSet rset = stmt.executeQuery(req);
			rset.next();
			numPlace = rset.getInt(1);
			rset.close();
			
			stmt.executeUpdate("INSERT INTO Contient(idAlbum, idPhoto, numPlace, titre, commentaire) VALUES (" + idAlbum + ",'"
																												 + idPhotos[list.getSelectionIndex()] + "','"
																												 + numPlace + 1 + "','"
																												 + text.getText().replace('\'', '_') + "','"
																												 + text_1.getText().replace('\'', '_') + "')");
	
			stmt.executeUpdate("COMMIT");
			rset.close();
			stmt.close();
			rafraichir();
		} catch (SQLException e) {
			MainApp.erreurBase(e.getMessage());
		}
	}
	
	public void rafraichirLesPhotos(){
		
		Statement stmt;
		list.removeAll();
		int idAlbum;
		

		if((btnAlbum.getSelection() && combo.getSelectionIndex() < 0) || (btnLivre.getSelection() && combo_1.getSelectionIndex() < 0))
			return;
		
		if(btnAlbum.getSelection())
			idAlbum = idAlbums[combo.getSelectionIndex()];
		else
			idAlbum = idLivres[combo_1.getSelectionIndex()];
		
		try {
			stmt = JDBC.getInstance().getStatement();
			stmt.executeUpdate("SET TRANSACTION READ ONLY");
			
			// On compte les albums de l'utilisateur
			String req = "SELECT COUNT(p.idPhoto) FROM Photo p, Contient c, Album" +
					" WHERE p.idPhoto NOT IN (SELECT idPhoto FROM Contient WHERE idAlbum = " + idAlbum + ")" +
					" AND ((p.idPhoto = c.idPhoto" +		// photo de l'utilisateur
					" AND c.idAlbum = Album.idAlbum" +
					" AND Album.idClient = " + MainApp.idClient +
					" ) OR (p.idPhoto = c.idPhoto" +	// photo partagée
					" AND c.idAlbum = Album.idAlbum" +
					" AND Album.partage LIKE 'o'))";
			ResultSet rset = stmt.executeQuery(req);
			if (rset.next()){
				idPhotos = new int[rset.getInt(1)];
			}
			rset.close();
			
			// On compte les livres de l'utilisateur
			req = "SELECT chemin, p.idPhoto FROM Photo p, Contient c, Album" +
					" WHERE p.idPhoto NOT IN (SELECT idPhoto FROM Contient WHERE idAlbum = " + idAlbum + ")" +
					" AND ((p.idPhoto = c.idPhoto" +		// photo de l'utilisateur
					" AND c.idAlbum = Album.idAlbum" +
					" AND Album.idClient = " + MainApp.idClient +
					" ) OR (p.idPhoto = c.idPhoto" +	// photo partagée
					" AND c.idAlbum = Album.idAlbum" +
					" AND Album.partage LIKE 'o'))" +
					" ORDER BY chemin";
			rset = stmt.executeQuery(req);
			int i = 0;
			while (rset.next()){
				idPhotos[i] = rset.getInt(2);
				list.add(rset.getString(1));
				i++;
			}
			stmt.executeUpdate("COMMIT");
			rset.close();
			stmt.close();
		} catch (SQLException e) {
			MainApp.erreurBase(e.getMessage());
		}
	}
	
	public void rafraichir(){
		
		Statement stmt;

		combo.removeAll();
		combo.setText("Choisissez un album");
		combo_1.removeAll();
		combo_1.setText("Choisissez un livre");
		list.removeAll();
		
		if(MainApp.estAdmin)
			btnAfficherLesStatistiques.setVisible(true);
		else
			btnAfficherLesStatistiques.setVisible(false);
		
		if(MainApp.idClient != 0){
			btnSeConnecter.setText("Déconnexion");
			lblVousNtesPas.setText(MainApp.prenom + " " + MainApp.nom);
		}else{
			shell.dispose();
			MainApp.consult.setActive();
			return;
		}
		try {
			stmt = JDBC.getInstance().getStatement();
			stmt.executeUpdate("SET TRANSACTION READ ONLY");
			
			// On compte les albums de l'utilisateur
			String req = "SELECT COUNT(titre) FROM Album WHERE idAlbum NOT IN (SELECT idAlbum FROM Livre) AND idClient = " + MainApp.idClient;
			ResultSet rset = stmt.executeQuery(req);
			if (rset.next()){
				idAlbums = new int[rset.getInt(1)];
			}
			rset.close();
			
			// On liste les albums de l'utilisateur
			req = "SELECT titre, idAlbum FROM Album WHERE idAlbum NOT IN (SELECT idAlbum FROM Livre) AND idClient = " + MainApp.idClient + " ORDER BY titre";
			rset = stmt.executeQuery(req);
			int i = 0;
			while (rset.next()){
				combo.add(rset.getString(1));
				idAlbums[i] = rset.getInt(2);
				i++;
			}
			rset.close();
			
			// On compte les livres de l'utilisateur
			req = "SELECT COUNT(titre) FROM Album WHERE idAlbum IN (SELECT idAlbum FROM Livre) AND idClient = " + MainApp.idClient;
			rset = stmt.executeQuery(req);
			if (rset.next()){
				idLivres = new int[rset.getInt(1)];
			}
			rset.close();
			
			// On liste les livres de l'utilisateur
			req = "SELECT titre, idAlbum FROM Album WHERE idAlbum IN (SELECT idAlbum FROM Livre) AND idClient = " + MainApp.idClient + " ORDER BY titre";
			rset = stmt.executeQuery(req);
			i = 0;
			while (rset.next()){
				combo_1.add(rset.getString(1));
				idLivres[i] = rset.getInt(2);
				i++;
			}
			rset.close();
			
			rafraichirLesPhotos();
			
			stmt.executeUpdate("COMMIT");
			rset.close();
			stmt.close();
		} catch (SQLException e) {
			MainApp.erreurBase(e.getMessage());
		}
	}
	
	/*
	 * Cette fonction retourne vrai si la fenêtre est déjà
	 * visible à l'écran
	 */
	public boolean estLance(){
		return shell != null && !shell.isDisposed();
	}
}
